
const { URL } = require("url");
const jwt = require("jsonwebtoken");
const noAuthApis = ['/api/v1/auth/getToken','/api/v1/baiduApi/picCategory','/api/v1/baiduApi/getAccessToken']; // 无需校验的api白名单
module.exports = (options) => {
  return async function adminauth(ctx, next) {
    const reqUrl = new URL(ctx.href); // 构建请求url 原  url.parse()方法已废弃
    const bearerToken = ctx.request.header.authorization; //获取token
    if (noAuthApis.includes(reqUrl.pathname)) {
      await next();
    } else if (bearerToken) {
      console.log('bearerToken是'+bearerToken)
      const token = bearerToken.replace("Bearer ", "");
      await jwt.verify(token, ctx.app.config.jwt.secret, async (err, res) => {
        if (err) {
          ctx.status = 401;
          ctx.body = {
            code: 2,
            data: err,
            msg: "token无效",
          };
        } else {
          const _LoginInfo = await ctx.app.redis.get(res.redisKey); // 根据email获取redis缓存的信息
          const loginUser = JSON.parse(_LoginInfo);
          if (
            loginUser &&
            loginUser.id
          ) {
            await next();
          } else {
            ctx.status = 401;
            ctx.body = {
              code: 1,
              data: null,
              msg: '身份校验不通过',
            };
          }
        }
      });
    } else {
      ctx.status = 401;
      ctx.body = {
        code: 1,
        data: null,
        msg: "无权限访问",
      };
    }
  };
};
